<template>
	<view class="main-container">
		<uni-card :border="none" padding="0" :is-shadow="false">
			<view class="autoAnalysis">
				<uni-easyinput type='textarea' v-model="totalInfomation" placeholder="试试粘贴收件人姓名、手机号、收货地址。可快速识别您的收货信息。" />
				<button class="analysisBtn" plain type="warn" size="mini" @click="analysisAddress">点击识别</button>
			</view>
			<uni-forms ref="modalForm" :modelValue="baseFormData" validateTrigger="blur">
				<uni-forms-item label="收货人" required :label-width="labelWidth" name="name">
					<uni-easyinput v-model="baseFormData.name" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="联系电话" required :label-width="labelWidth" name="phone">
					<uni-easyinput v-model="baseFormData.phone" placeholder="请输入电话" />
				</uni-forms-item>
				<uni-forms-item label="所在地区" required :label-width="labelWidth" name="city">
					<lb-picker ref="picker1" v-model="value3" mode="multiSelector" :list="list" :level="3"
						:dataset="{ name: 'label3' }" @confirm="pickerConfirm" @cancel="pickerCancel">
						<uni-easyinput class="un-disabled" disabled v-model="baseFormData.city" placeholder="请点击选择" />
					</lb-picker>
				</uni-forms-item>
				<uni-forms-item label="详细地址" required :label-width="labelWidth" name="detail">
					<uni-easyinput type='textarea' v-model="baseFormData.detail" placeholder="请输入详细地址" />
				</uni-forms-item>
			</uni-forms>
		</uni-card>
		<u-button text="保存地址" shape="circle" type="error" @click="saveAddressConfirm('modalForm')"></u-button>
	</view>
</template>

<script>
	import AddressParse from 'address-parse'
	import cityData from "@/utils/area-data-min.js"
	import {
		saveAddress
	} from "@/utils/wx_address"
	export default {
		data() {
			return {
				totalInfomation: "",
				labelWidth: 80,
				list: cityData,
				value3: [],
				label3: '',
				baseFormData: {
					openid: uni.getStorageSync('openid'),
					name: "",
					phone: "",
					city: "",
					detail: ""
				},
				cityProps: {
					label: 'name',
					value: 'code',
					children: 'children'
				},
				rules: {
					name: {
						rules: [{
								required: true,
								errorMessage: '请输入名称',
							},
							{
								minLength: 2,
								maxLength: 30,
								errorMessage: '长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入联系人电话',
						}, {
							validateFunction: function(rule, value, data, callback) {
								let iphoneReg = /^1[3456789]\d{9}$/
								let landlineReg = /0\d{2,3}-\d{7,8}/
								const flagArr = []
								flagArr.push(iphoneReg.test(value))
								flagArr.push(landlineReg.test(value))
								if (!flagArr.includes(true)) {
									callback('手机号码格式不正确，请重新填写')
								}
								return true
							}
						}]
					},
					city: {
						rules: [{
							required: true,
							errorMessage: '请选择所在地',
						}, {
							validateFunction: function(rule, value, data, callback) {
								const regex = /^([\u4E00-\u9FA5]+)-([\u4E00-\u9FA5]+)(-([\u4E00-\u9FA5]+))?$/;
								// 使用正则表达式进行匹配
								const match = value.match(regex) || "";
								// console.log(match, value, data)
								if (match === "") {
									callback('请完善地区信息，格式为“省-市-区”')
								}
								return true
							}
						}]
					},
					detail: {
						rules: [{
							required: true,
							errorMessage: '请输入详细地址',
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.modalForm.setRules(this.rules)
		},
		onLoad(options) {
			this.baseFormData = JSON.parse(decodeURIComponent(options.data))
		},
		methods: {
			analysisAddress() {
				/*判断解析的地址内容不为空*/
				if (this.totalInfomation != '') {
					const result = AddressParse.parse(this.totalInfomation);
					this.baseFormData.name = result[0].name;
					this.baseFormData.phone = result[0].mobile;
					this.baseFormData.city = `${result[0].province}-${result[0].city}-${result[0].area}`
					this.baseFormData.detail = result[0].details;
					console.log(this.baseFormData)
				} else {
					uni.showToast({
						title: '不能为空',
						icon: 'error'
					})
				}
			},
			pickerConfirm(e) {
				// 如果存在多个picker，可以在picker上设置dataset属性，confirm中获取，就能区分是哪个picker了
				// console.log('confirm::', e)
				if (e) {
					const name = e.dataset.name
					const label = e.item.map(m => m.label).join('-')
					if (name && label) {
						this.baseFormData.city = label
					}
				}
			},
			pickerCancel() {
				console.log('cancel')
			},
			async saveAddressConfirm(ref) {
				try {
					await this.$refs[ref].validate()
					console.log(this.baseFormData)
					let res = await saveAddress(this.baseFormData)
					uni.showToast({
						title: this.baseFormData.id ? "修改成功" : "新增成功",
						icon: 'success',
						duration: 1000,
						success: (res) => {
							setTimeout(() => {
								uni.navigateBack()
							}, 1200)
						}
					})
				} catch (e) {
					console.log(e, 'error')
					//TODO handle the exception
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.main-container {
		min-height: 100vh;
		margin: 0;
		box-sizing: border-box;
		padding: 3vw;
		background-color: #f7f7f7;
	}

	/deep/ .uni-card {
		font-size: 32rpx !important;
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 0 40rpx 0 !important;
		padding: 30rpx !important;

		.autoAnalysis {
			margin-bottom: 30rpx;
			position: relative;
		}

		.analysisBtn {
			position: absolute;
			right: 20rpx;
			bottom: 20rpx;
			z-index: 99;
		}

		.is-disabled {
			background-color: #fff !important;
			border-color: #e5e5e5 !important;
			color: #333 !important;

			.uni-easyinput__placeholder-class {
				color: #999 !important;
			}
		}
	}
</style>